﻿/*
Copyright (c) Microsoft Corporation

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0   

THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.  

See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. 
*/

(function () {
    "use strict";
    WinJS.Namespace.define("Livetile", {
        updateLiveTile: updateLiveTile,
        live_tile_src: live_tile_src,
        hiker_data_array: []
    });

    function updateLiveTile() {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var yetiImg = new Image();
        var blobDataArray = [];
        var yetiData = DataYeti.data;


        var sliceStart = (Math.floor(Math.random() * DataHikers.filtered.length));
        sliceStart = Math.min(Math.max(parseInt(sliceStart), 0), (DataHikers.filtered.length - 3));
        var sliceEnd = sliceStart + 3;
        // get slice of hikers for live tiles
        var hikerDataArray = DataHikers.filtered.slice(sliceStart, sliceEnd);
        Livetile.hiker_data_array = hikerDataArray;
        // add the yeti data to the live tile array
        Livetile.hiker_data_array.push(yetiData)
        Livetile.hiker_data_array.reverse();

        //clear out current tiles
        Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().clear();

        // Enable the notification queue
        Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueue(true);


        for (var i = 0; i < hikerDataArray.length; i++) { // loop though array make msBlobs from images 
            var imgload_index = 0;
            var img = new Image();
            var data = hikerDataArray[i];
            img.onload = function (e) {
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                canvas.width = this.width;
                canvas.height = this.height;
                ctx.drawImage(this, 0, 0);
                blobDataArray.push({ data_index: imgload_index, blobData: canvas.msToBlob() });
                imgload_index++;
                if (blobDataArray.length == hikerDataArray.length) {
                    makeLiveTilesFromArray(blobDataArray);
                }
            };
            img.src = hikerDataArray[i].profile_pic;
        };

    };

    function makeLiveTilesFromArray(blobDataArray) {
        for (var n = 0; n < blobDataArray.length; n++) { // loop though array, create tiles
            var b = blobDataArray[n];
            var data = Livetile.hiker_data_array[b.data_index];
            createFileUpdateTile(data, b.blobData);
        };
    };

    function createFileUpdateTile(data, blob) {
        //Save blob to image
        if (!blob) {
            return false;
        };
        var out = null;
        var blobStream = null;
        var outputStream = null;
        var id = data.id;

        // save image file to disk, then create tile
        Windows.Storage.ApplicationData.current.localFolder.createFileAsync("#.png".replace('#', id), Windows.Storage.CreationCollisionOption.replaceExisting)
            .then(function (file) {
                // create stream
                return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
            })
            .then(function (stream) {
                outputStream = stream;
                out = stream.getOutputStreamAt(0);
                blobStream = blob.msDetachStream();
                return Windows.Storage.Streams.RandomAccessStream.copyAsync(blobStream, out);
            })
            .then(function () {
                return out.flushAsync();
            })
            .done(function () {
                blobStream.close();
                out.close();
                outputStream.close();

                // create/add tile
                var notifications = Windows.UI.Notifications;
                var template = notifications.TileTemplateType.tileWideSmallImageAndText02;
                var tileXml = notifications.TileUpdateManager.getTemplateContent(template);
                var title = (data.title.search(/customize your yeti/gi) > -1 ? 'Yeti Stats' : data.title);
                var image = tileXml.getElementsByTagName("image")[0];
                var line1 = tileXml.getElementsByTagName("text")[0];
                var line2 = tileXml.getElementsByTagName("text")[1];
                var line3 = tileXml.getElementsByTagName("text")[2];
                var binding = tileXml.getElementsByTagName('binding')[0];


                image.setAttribute("src", "ms-appdata:///local/#.png".replace('#', id));
                line1.appendChild(tileXml.createTextNode(title));

                if (typeof(data.stats.deaths) != 'undefined') {
                    line2.appendChild(tileXml.createTextNode('Killed # times'.replace('#', data.stats.deaths)));
                    line3.appendChild(tileXml.createTextNode('Reached the top # times'.replace('#', data.stats.wins)));
                } else {
                    line2.appendChild(tileXml.createTextNode('Highest score: #'.replace('#', data.stats.highscore)));
                    line3.appendChild(tileXml.createTextNode('Climbers Killed: #'.replace('#', data.stats.kills)));
                }

                var tileNotification = new notifications.TileNotification(tileXml);
                notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification);
            });

    };

    var has_custom_tile = false;
    var live_tile_src = 'ms-appx:///images/livetile.png';

})();

